package org.jiangy.usercenter.entity;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.hibernate.annotations.ColumnDefault;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;
import org.jiangy.authentication.DefaultGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.io.Serializable;
import java.time.Instant;
import java.util.Collection;
import java.util.HashSet;

/**
 * 用户
 * <p>创建时间: 2024/8/13 </p>
 *
 * @author <a href="mailto:jiangliu0316@outlook.com" rel="nofollow">蒋勇</a>
 */
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, property = "classType")
@JsonSubTypes({
        @JsonSubTypes.Type(value = Customer.class, name = "Customer"),
        @JsonSubTypes.Type(value = Staff.class, name = "Staff")
})
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Table(
        indexes = {
                @Index(name = "idx_username", columnList = "username", unique = true),
                @Index(name = "idx_type", columnList = "type")
        }
)
public abstract class User implements UserDetails, Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "is_account_non_expired", columnDefinition = "tinyint(1) DEFAULT 1")
    private boolean accountNonExpired;
    @Column(name = "is_account_non_locked", columnDefinition = "tinyint(1) DEFAULT 1")
    private boolean accountNonLocked;
    @Column(name = "is_credentials_non_expired", columnDefinition = "tinyint(1) DEFAULT 1")
    private boolean credentialsNonExpired;

    @Column(unique = true)
    private String username;
    @JsonIgnore
    private String password;

    private String avatar;
    /**
     * 用户来源（customer、staff）
     */
    @Convert(converter = UserTypeConverter.class)
    private UserTypeEnum type;

    @Column(name = "is_enabled", columnDefinition = "tinyint(1) DEFAULT 1")
    private boolean enabled;

    private String registeredIp;
    private String registeredLocation;
    private Instant registeredAt;

    private String lastLoginIp;
    private String lastLoginLocation;
    private Instant lastLoginAt;

    private String creator;
    private String creatorId;

    @CreationTimestamp
    private Instant createdAt;

    private String modifier;
    private String modifierId;

    @UpdateTimestamp
    private Instant modifiedAt;

    @ColumnDefault("0")
    private boolean isDeleted;
    private Instant deletedAt;

    @Transient
    private Collection<DefaultGrantedAuthority> authorities = new HashSet<>();
}
